/*
 * NIST Healthcare Test Framework
 * MllpUtils.java Jul 26, 2010
 *
 * This code was produced by the National Institute of Standards and
 * Technology (NIST). See the "nist.disclaimer" file given in the distribution
 * for information on the use and redistribution of this software.
 */
package gov.nist.healthcare.testframework.communication;

import gov.nist.healthcare.core.message.HL7Message;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;

/**
 * This class contains methods to deal with the MLLP protocol.
 * 
 * @author Sydney Henrard (NIST)
 */
public class MllpUtils {

    public static final char VT = 0x0b;
    public static final char FS = 0x1c;
    public static final char CR = 0x0d;

    /**
     * Wrap a message with the MLLP wrappers
     * 
     * @param message
     * @return the wrapped message
     */
    public static String wrapMessage(HL7Message message) {
        return VT + message.getMessageAsString() + FS + CR;
    }

    /**
     * Unwrap a message
     * 
     * @param message
     * @return the unwrapped message
     */
    public static String unWrapMessage(String message) {
        return message.substring(1, message.length() - 3);
    }

    /**
     * Extract the message from the input stream
     * 
     * @param in
     * @return the message
     * @throws IOException
     */
    public static String extractMessage(InputStream in) throws IOException {
        StringWriter inBuf = new StringWriter();
        int c = 0;
        boolean gotFS = false;
        boolean newMessage = false;
        while ((c = in.read()) != -1) {
            /* ignore everything till we see, start of new message char */
            if (!newMessage) {
                if (c == MllpUtils.VT) {
                    newMessage = true;
                    continue;
                }
            }
            /* see if we're done */
            if (gotFS) {
                if (c == MllpUtils.CR) {
                    break;
                } else {
                    /*
                     * don't think FS can be part of msg, but if we didn't get a
                     * CR, we have to assume it is
                     */
                    inBuf.write(MllpUtils.FS);
                }
            }
            /* check for field separator char */
            if (c == MllpUtils.FS) {
                gotFS = true;
                continue;
            } else {
                gotFS = false;
            }
            if (c != MllpUtils.VT)
                inBuf.write(c);
        }
        return inBuf.toString();
    }

}
